import Vue from 'vue'
export default {
    namespaced:true,
    state: {
        goods:[], //菜单信息
        cartFoods:[], //购物车食物列表
        info:{}, //商品信息
        ratings:[], //评价信息
    },
    getters:{
        //总数量
        totalCount (state) {
            return state.cartFoods.reduce((preTotal, food) => preTotal + food.count , 0)
        },
        //总价格
        totalPrice (state) {
            return state.cartFoods.reduce((preTotal, food) => preTotal + food.count*food.price , 0)
        },
        positiveSize (state) {
            return state.ratings.reduce((preTotal, rating) => preTotal + (rating.rateType===0?1:0) , 0)
        }
    },
    mutations: {
        //商品信息
        receive_goods(state,goods){
            state.goods=goods
        },
        //商家信息
        receive_info(state,info){
            state.info=info
            // console.log(info)
        },
        //评价信息
        receive_ratings(state,ratings){
            state.ratings=ratings
        },
        //购物车里面食物数量
        inc_footcount(state, {food}) {
            if(!food.count) { // 第一次增加
                // food.count = 1  // 新增属性(没有数据绑定)
                /*
                对象 属性名属性值 
                 */
                Vue.set(food, 'count', 1) // 让新增的属性也有数据绑定
                state.cartFoods.push(food)  // 将food添加到cartFoods中
            } else {
                food.count++
            }
        },
        dec_footcount(state, {food}) {  //购物车数量减减
            if(food.count) {// 只有有值才去减
                food.count--
                if(food.count===0) {
                    // 将food从cartFoods中移除
                    state.cartFoods.splice(state.cartFoods.indexOf(food), 1)
                }
            }
        },
        //清除购物车
        clear_cart(state) {
            // 清除food中的count
            state.cartFoods.forEach(food => food.count = 0)
            // 移除购物车中所有购物项
            state.cartFoods = []
        },
    },
    actions: {
        receive_goods({commit},goods){ //商品
            commit('receive_goods',goods)
        },
        receive_info({commit},info){   //商家信息
            // const ret = await this.$axios.get('/info')
            // console.log(ret)
            //     const info=ret.data.data
            //     commit('receive_info',info)
            commit('receive_info',info)
            console.log('123')
            sessionStorage.setItem('info',JSON.stringify(info))
        },
        receive_ratings({commit},ratings){  //评价信息
            commit('receive_ratings',ratings)
        },
        //更新goods里面的foot数量
        updateFoodCount({commit}, {isAdd, food}) {
            if (isAdd) {
                commit('inc_footcount', {food})
            } else {
                commit('dec_footcount', {food})
            }
        },
        // 同步清空购物车
        clearCart({commit}) {
            commit('clear_cart')
        },
    },
  }







